<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录接口测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 Uniflow平台登录接口测试</h1>
        
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" value="admin" placeholder="请输入用户名">
        </div>
        
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" value="admin123" placeholder="请输入密码">
        </div>
        
        <div class="form-group">
            <button onclick="testLogin()" id="loginBtn">🚀 测试登录</button>
            <button onclick="checkAuthStatus()">📊 检查认证状态</button>
            <button onclick="testLogout()">🚪 测试登出</button>
            <button onclick="clearResults()">🧹 清空结果</button>
        </div>
        
        <div class="status" id="authStatus">
            <strong>认证状态:</strong> <span id="statusText">未登录</span>
        </div>
        
        <div id="results"></div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8080/api/v1';
        
        // 模拟简单的认证状态管理
        let authState = {
            user: null,
            token: null,
            isAuthenticated: false
        };
        
        // 更新认证状态显示
        function updateAuthStatus() {
            const statusText = document.getElementById('statusText');
            const token = localStorage.getItem('auth-token');
            const user = localStorage.getItem('auth-user');
            
            if (token && user) {
                try {
                    const userData = JSON.parse(user);
                    statusText.innerHTML = `已登录 - 用户: ${userData.name} (${userData.email}) | Token: ${token.substring(0, 20)}...`;
                    authState.isAuthenticated = true;
                    authState.user = userData;
                    authState.token = token;
                } catch (e) {
                    statusText.innerHTML = '认证状态异常';
                    authState.isAuthenticated = false;
                }
            } else {
                statusText.innerHTML = '未登录';
                authState.isAuthenticated = false;
                authState.user = null;
                authState.token = null;
            }
        }
        
        // 添加结果显示
        function addResult(message, type = 'info') {
            const results = document.getElementById('results');
            const resultDiv = document.createElement('div');
            resultDiv.className = `result ${type}`;
            resultDiv.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            results.appendChild(resultDiv);
            results.scrollTop = results.scrollHeight;
        }
        
        // 测试登录功能
        async function testLogin() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginBtn');
            
            if (!username || !password) {
                addResult('请输入用户名和密码', 'error');
                return;
            }
            
            loginBtn.disabled = true;
            loginBtn.textContent = '登录中...';
            
            try {
                addResult(`开始登录测试 - 用户名: ${username}`, 'info');
                
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                addResult(`HTTP状态码: ${response.status} ${response.statusText}`, 'info');
                
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }
                
                const data = await response.json();
                addResult(`后端原始响应: ${JSON.stringify(data, null, 2)}`, 'info');
                
                // 模拟前端数据适配逻辑
                const adaptedResponse = {
                    token: data.accessToken,
                    refreshToken: data.refreshToken,
                    expiresIn: data.expiresIn,
                    user: {
                        id: data.user.id,
                        name: data.user.displayName,
                        email: data.user.email,
                        organizationId: data.user.orgId,
                        status: data.user.status === 1 ? 'active' : 'inactive'
                    }
                };
                
                // 保存到localStorage
                localStorage.setItem('auth-token', adaptedResponse.token);
                localStorage.setItem('auth-user', JSON.stringify(adaptedResponse.user));
                
                addResult(`✅ 登录成功!\n适配后数据: ${JSON.stringify(adaptedResponse, null, 2)}`, 'success');
                updateAuthStatus();
                
            } catch (error) {
                addResult(`❌ 登录失败: ${error.message}`, 'error');
                console.error('Login error:', error);
            } finally {
                loginBtn.disabled = false;
                loginBtn.textContent = '🚀 测试登录';
            }
        }
        
        // 检查认证状态
        function checkAuthStatus() {
            updateAuthStatus();
            const token = localStorage.getItem('auth-token');
            const user = localStorage.getItem('auth-user');
            
            if (token && user) {
                addResult(`当前认证状态:\nToken: ${token}\nUser: ${user}`, 'info');
            } else {
                addResult('当前未登录', 'info');
            }
        }
        
        // 测试登出
        function testLogout() {
            localStorage.removeItem('auth-token');
            localStorage.removeItem('auth-user');
            authState = { user: null, token: null, isAuthenticated: false };
            updateAuthStatus();
            addResult('✅ 已登出，清除本地存储', 'success');
        }
        
        // 清空结果
        function clearResults() {
            document.getElementById('results').innerHTML = '';
        }
        
        // 页面加载时检查认证状态
        window.onload = function() {
            updateAuthStatus();
            addResult('页面加载完成，可以开始测试登录功能', 'info');
        };
        
        // 监听回车键登录
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                testLogin();
            }
        });
    </script>
</body>
</html>